package com.spring.http;

import com.spring.utils.HttpProtocolUtil;
import com.spring.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Spring King
 * @date 2021/7/10
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void output(String context) throws IOException {
        outputStream.write(context.getBytes(StandardCharsets.UTF_8));
    }


    public void outputHtml(String path) throws IOException {
        String abPath = StaticResourceUtil.getAbPath(path);
        File file = new File(abPath);
        if (file.exists() && file.isFile()) {
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
